package com.congwulin.wechat.util.service.bill;

import com.congwulin.wechat.entity.common.AbstractMeBillVO;
import com.congwulin.wechat.entity.common.SuperVO;
import com.congwulin.wechat.util.*;
import com.congwulin.wechat.util.interfaces.AbstractBillService;
import com.congwulin.wechat.util.interfaces.IBillPersistent;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class BillInsertService extends AbstractBillService {
    /**
     * 一主多子实体抽象服务构造函数
     *
     * @param dao 一主多子实体保存数据库器
     */
    public BillInsertService(IBillPersistent dao) {
        super(dao);
    }

    /**
     * 新增一主多子实体数组
     *
     * @param vos
     *            一主多子实体数组
     */
    public List<?> insert(AbstractMeBillVO[] vos) {
        List<AbstractMeBillVO> list = Arrays.asList(vos);
        return this.insert(list);
    }

    /**
     * 新增一主多子实体列表
     *
     * @param list
     *            一主多子实体列表
     *
     */
    @SuppressWarnings("unchecked")
    public List<?> insert(List<?> list) {
        List<AbstractMeBillVO> paralist = (List<AbstractMeBillVO>) list;

        BillTool tool = new BillTool();
        tool.setStatus(paralist, EntityConst.INSERT);

        // 设置新增审计信息
        this.setNewAuditInfo(paralist);
        // DR=0
        this.setDr(paralist);
        try {
            this.getDAO().insert(paralist);
        } catch (Exception ex) {
            // 继续向上抛出异常
            ExceptionUtils.wrapException(ex);
        }
        return list;
    }

    /**
     * 设置创建人创建时间，包括表头表体
     * @param list
     */
    private void setNewAuditInfo(List<AbstractMeBillVO> list) {
        // 创建时间
        Timestamp creationtime = new Timestamp(System.currentTimeMillis());
        // 创建人
        UserInfoUtil util = SpringUtil.getBean(UserInfoUtil.class);
        String creator = util.getContent().getId();
        String creatorname = util.getContent().getName();
        for (AbstractMeBillVO bill : list) {
            SuperVO head = bill.getHead();
            head.setCreationtime(creationtime);
            head.setCreator(creator);

            Map<Class<?>, List<SuperVO>> bodys = bill.getChildrens();

            for (List<SuperVO> vos : bodys.values()) {
                for (SuperVO vo : vos) {
                    vo.setCreationtime(creationtime);
                    vo.setCreator(creator);
                    vo.setCreator_name(creatorname);
                }
            }
        }
    }

    /**
     * 设置默认dr
     *
     * @param list
     */
    private void setDr(List<AbstractMeBillVO> list) {
        for (AbstractMeBillVO bill : list) {
            SuperVO head = bill.getHead();
            head.setDr(0);

            Map<Class<?>, List<SuperVO>> bodys = bill.getChildrens();

            for (List<SuperVO> vos : bodys.values()) {
                for (SuperVO vo : vos) {
                    vo.setDr(0);
                }
            }
        }

    }
}
